﻿// Batch Rename v1.0.1
// Made by mishaor with thanks to SharpDevelop
using System;    
using System.IO;

namespace BatchRename 
{
	class Program
	{
		public static int Main(string[] args)
		{
			if(args.Length == 0)
			{
				// If no arguments, we printing help message and exitting with return code 0
				Console.WriteLine("Batch Rename v1");
				Console.WriteLine("Made with love by mishaor (Michael Orishich)");
				Console.WriteLine("Usage: BatchRename [folder path] [what to replace] [with what replace]");
				Console.WriteLine("Folder path can be:");
				Console.WriteLine("- folder path");
				Console.WriteLine("- .\\, which means current directory");
				return 0;
			}
			else 
			{
				string[] fileList = null; // we creating array with null because we can't get variable from try
				// we writing information about program and file path
				Console.WriteLine("Batch Rename v1");
				Console.WriteLine("Made with love by mishaor (Michael Orishich)");
				Console.WriteLine("Folder Path: {0}", args[0]);
				// we getting file list from specified directory
				try
				{
					fileList = Directory.GetFiles(args[0]); // we getting file list from directory in arguments
				}
				catch(Exception error)
				{
					Console.WriteLine("Error when getting file list of {0}: {1}", args[0], error.Message); // if error happened, we printing message 
					Environment.Exit(-1); // ...aaaand exiting program with code -1 
				}
				foreach(string filePath in fileList) // for each file in file list we executing this code
				{
					string fileName = Path.GetFileName(filePath); // we getting file name from file list
					if(fileName.Contains(args[1])) // if name contains piece to replace
					{
						// ...then we replacing it!
						try
						{
							File.Move(filePath, filePath.Replace(args[1], args[2])); // we renaming file from original to original with needed replacement (sorry for my english)
						}
						catch(Exception error) 
						{
							Console.WriteLine("Error when renaming file {0}: {1}", fileName, error.Message); // if error happened, we printing messsage
							break; // ...and ignore it by doing break which get us back
						}
						Console.WriteLine("Successfully renamed {0} with {1}", fileName, fileName.Replace(args[1], args[2])); // if we renamed sucessfully, we printing message
					}
				}
				return 0; // we returning 0 if all is OK
			}
		}
	}
}